import { defineStore } from "pinia"
import router from "@/router"
import { MENU_LIST } from "@/constants"
import { mapMenusToRoutes } from "@/utils/menu"

interface HomeState {
  menuTabs: MenuTab[]
  showComSearch: boolean
}

const useHomeStore = defineStore("home", {
  state: (): HomeState => ({
    menuTabs: [],
    showComSearch: false
  }),
  actions: {
    loadLocalCacheAction() {
      const menuList = JSON.parse(localStorage.getItem(MENU_LIST) || "[]")
      if (menuList) {
        const routes = mapMenusToRoutes(menuList)
        for (const route of routes) {
          // 动态添加路由
          router.addRoute("home", route)
        }
      }
    },
    addMenuTabAction(tab: MenuTab) {
      this.menuTabs.push(tab)
    },
    removeMenuTabAction(path: string) {
      this.menuTabs = this.menuTabs.filter((tab) => tab.path !== path)
    },
    setShowComSearchAction() {
      this.showComSearch = !this.showComSearch
    }
  }
})

export default useHomeStore
